home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 25 / Cream of the Crop 25.iso / utility / ffe101.zip / GRAPH.SWG / 0004_GIF (LZW) EXPLANATION.pas < prev    next >
Pascal/Delphi Source File  |  1996-09-04  |  48KB  |  1,097 lines

  1.  
  2.  
  3.                    LZW and GIF explained----Steve Blackstock
  4.  
  5.  
  6.       I  hope this little document will  help enlighten those of you out
  7. there  who  want  to know more  about  the  Lempel-Ziv Welch compression
  8. algorithm,  and, specifically, the implementation  that GIF uses. Before
  9. we  start,  here's  a  little  terminology,  for  the  purposes  of this
  10. document:
  11.  
  12.       "character":  a  fundamental data element.  In  normal text files,
  13. this  is  just  a  single byte. In  raster  images,  which is what we're
  14. interested  in, it's an index that specifies the color of a given pixel.
  15. I'll  refer  to an arbitray character  as "K". "charstream": a stream of
  16. characters,  as  in  a  data  file.  "string":  a  number  of continuous
  17. characters,  anywhere from one to very  many characters in length. I can
  18. specify  an arbitrary string as "[...]K". "prefix": almost the same as a
  19. string,  but  with the implication that  a prefix immediately precedes a
  20. character,  and  a prefix can have a length  of zero. So, a prefix and a
  21. character  make  up  a string. I will  refer  to  an arbitrary prefix as
  22. "[...]". "root": a single-character string. For most purposes, this is a
  23. character,  but  we may occasionally make  a  distinction. It is [...]K,
  24. where  [...] is empty. "code": a number,  specified by a known number of
  25. bits,  which maps to a string. "codestream": the output stream of codes,
  26. as  in the "raster data" "entry": a code and its string. "string table":
  27. a  list of entries; usually, but not necessarily, unique. That should be
  28. enough of that.
  29.  
  30.      LZW is a way of compressing data that takes advantage of repetition
  31. of strings in the data. Since raster data usually contains a lot of this
  32. repetition,  LZW is a good way  of compressing and decompressing it. For
  33. the  moment,  lets  consider  normal  LZW  encoding  and decoding. GIF's
  34. variation   on  the  concept  is  just  an  extension  from  there.  LZW
  35. manipulates  three  objects in both  compression  and decompression: the
  36. charstream,  the  codestream, and the  string table. In compression, the
  37. charstream   is  the  input  and  the   codestream  is  the  output.  In
  38. decompression,  the  codestream is the input  and  the charstream is the
  39. output.   The  string  table  is  a  product  of  both  compression  and
  40. decompression,  but  is  never passed from  one  to the other. The first
  41. thing  we  do in LZW compression is  initialize  our string table. To do
  42. this,  we  need to choose a code size  (how many bits) and know how many
  43. values  our characters can possibly take. Let's  say our code size is 12
  44. bits,  meaning we can store 0->FFF, or 4096 entries in our string table.
  45. Lets  also  say  that we have  32  possible  different characters. (This
  46. corresponds  to,  say, a picture in  which there are 32 different colors
  47. possible  for  each  pixel.) To initialize  the  table, we set code#0 to
  48. character#0,  code  #1  to  character#1, and  so  on,  until  code#31 to
  49. character#31.  Actually,  we are specifying that  each code from 0 to 31
  50. maps  to  a root. There will be no  more  entries in the table that have
  51. this  property.  Now  we  start  compressing  data.  Let's  first define
  52. something  called  the "current prefix". It's  just  a prefix that we'll
  53. store  things in and compare things to now  and then. I will refer to it
  54. as  "[.c.]". Initially, the current prefix has nothing in it. Let's also
  55. define  a  "current string", which will  be  the current prefix plus the
  56. next  character in the charstream. I will refer to the current string as
  57. "[.c.]K",  where K is some character. OK, look at the first character in
  58. the  charstream.  Call  it P. Make  [.c.]P  the current string. (At this
  59. point,  of course, it's just the root  P.) Now search through the string
  60. table  to  see if [.c.]P appears in  it. Of course, it does now, because
  61. our  string  table  is  initialized to have  all  roots.  So we don't do
  62. anything. Now make [.c.]P the current prefix. Look at the next character
  63. in  the  charstream.  Call it Q. Add  it  to  the current prefix to form
  64. [.c.]Q,  the current string. Now search  through the string table to see
  65. if  [.c.]Q appears in it. In this  case, of course, it doesn't. Aha! Now
  66. we  get  to do something. Add [.c.]Q (which  is  PQ in this case) to the
  67. string  table  for  code#32,  and  output  the  code  for  [.c.]  to the
  68. codestream.  Now start over again with the current prefix being just the
  69. root  P. Keep adding characters to [.c.] to form [.c.]K, until you can't
  70. find  [.c.]K in the string table. Then output the code for [.c.] and add
  71. [.c.]K to the string table. In pseudo-code, the algorithm goes something
  72. like this:
  73.  
  74.      [1] Initialize string table;
  75.      [2] [.c.] <- empty;
  76.      [3] K <- next character in charstream;
  77.      [4] Is [.c.]K in string table?
  78.       (yes: [.c.] <- [.c.]K;
  79.             go to [3];
  80.       )
  81.       (no: add [.c.]K to the string table;
  82.            output the code for [.c.] to the codestream;
  83.            [.c.] <- K;
  84.            go to [3];
  85.       )
  86.  
  87.        It's  as simple as that! Of course,  when you get to step [3] and
  88. there  aren't  any  more characters left,  you  just output the code for
  89. [.c.]  and throw the table away. You're done. Wanna do an example? Let's
  90. pretend we have a four-character alphabet: A,B,C,D. The charstream looks
  91. like  ABACABA. Let's compress it. First,  we initialize our string table
  92. to:  #0=A,  #1=B, #2=C, #3=D. The first  character is A, which is in the
  93. string  table,  so [.c.] becomes A. Next we  get AB, which is not in the
  94. table,  so we output code #0 (for [.c.]), and add AB to the string table
  95. as  code  #4. [.c.] becomes B. Next we  get [.c.]A = BA, which is not in
  96. the  string table, so output code #1, and  add BA to the string table as
  97. code  #5.  [.c.] becomes A. Next we get  AC,  which is not in the string
  98. table.  Output  code #0, and add AC to  the string table as code #6. Now
  99. [.c.]  becomes  C. Next we get [.c.]A =  CA,  which is not in the table.
  100. Output  #2  for C, and add CA to  table  as code#7. Now [.c.] becomes A.
  101. Next  we get AB, which IS in the  string table, so [.c.] gets AB, and we
  102. look  at  ABA, which is not in the  string table, so output the code for
  103. AB,  which  is  #4, and add ABA to  the  string  table as code #8. [.c.]
  104. becomes  A.  We can't get any more  characters, so we just output #0 for
  105. the  code  for A, and we're done.  So, the codestream is #0#1#0#2#4#0. A
  106. few  words  (four) should be said  here  about efficiency: use a hashing
  107. strategy.  The  search through the  string  table can be computationally
  108. intensive,  and  some hashing is well  worth the effort. Also, note that
  109. "straight LZW" compression runs the risk of overflowing the string table
  110. -  getting  to a code which can't  be  represented in the number of bits
  111. you've  set aside for codes. There are several ways of dealing with this
  112. problem, and GIF implements a very clever one, but we'll get to that. An
  113. important  thing to notice is that, at any point during the compression,
  114. if  [...]K  is  in  the string table,  [...]  is  there  also. This fact
  115. suggests  an  efficient method for storing  strings in the table. Rather
  116. than  store  the  entire string of K's  in  the  table, realize that any
  117. string  can be expressed as a prefix  plus a character: [...]K. If we're
  118. about to store [...]K in the table, we know that [...] is already there,
  119. so  we can just store the code for [...] plus the final character K. Ok,
  120. that  takes care of compression. Decompression is perhaps more difficult
  121. conceptually, but it is really easier to program. Here's how it goes: We
  122. again  have to start with an  initialized string table. This table comes
  123. from what knowledge we have about the charstream that we will eventually
  124. get,  like  what possible values the  characters can take. In GIF files,
  125. this  information  is  in  the header  as  the  number of possible pixel
  126. values.  The beauty of LZW, though, is that this is all we need to know.
  127. We  will  build  the  rest  of the  string  table  as  we decompress the
  128. codestream.  The  compression is done in such  a  way that we will never
  129. encounter  a  code  in  the codestream  that  we  can't translate into a
  130. string.  We  need to define something  called  a "current code", which I
  131. will  refer to as "<code>", and an  "old-code", which I will refer to as
  132. "<old>".  To  start  things  off, look at  the  first  code. This is now
  133. <code>. This code will be in the intialized string table as the code for
  134. a  root. Output the root to the  charstream. Make this code the old-code
  135. <old>.  *Now  look at the next code,  and make it <code>. It is possible
  136. that this code will not be in the string table, but let's assume for now
  137. that it is. Output the string corresponding to <code> to the codestream.
  138. Now  find  the first character in  the  string you just translated. Call
  139. this  K.  Add this to the prefix [...]  generated by <old> to form a new
  140. string  [...]K. Add this string [...]K to  the string table, and set the
  141. old-code <old> to the current code <code>. Repeat from where I typed the
  142. asterisk,  and  you're  all set. Read  this  paragraph again if you just
  143. skimmed  it!!! Now let's consider the  possibility that <code> is not in
  144. the  string table. Think back to compression, and try to understand what
  145. happens  when  you  have  a string  like  P[...]P[...]PQ  appear  in the
  146. charstream.  Suppose P[...] is already in  the string table, but P[...]P
  147. is  not. The compressor will parse out  P[...], and find that P[...]P is
  148. not  in  the string table. It will  output  the code for P[...], and add
  149. P[...]P to the string table. Then it will get up to P[...]P for the next
  150. string,  and find that P[...]P is in  the table, as the code just added.
  151. So  it will output the code for P[...]P if it finds that P[...]PQ is not
  152. in  the  table.  The  decompressor  is  always  "one  step  behind"  the
  153. compressor. When the decompressor sees the code for P[...]P, it will not
  154. have  added  that  code to it's string  table  yet because it needed the
  155. beginning  character of P[...]P to add to  the string for the last code,
  156. P[...], to form the code for P[...]P. However, when a decompressor finds
  157. a  code that it doesn't know yet, it will always be the very next one to
  158. be added to the string table. So it can guess at what the string for the
  159. code  should  be,  and, in fact, it will  always  be  correct. If I am a
  160. decompressor,  and  I see code#124, and  yet my string table has entries
  161. only  up to code#123, I can figure out  what code#124 must be, add it to
  162. my  string  table,  and  output the  string.  If  code#123 generated the
  163. string, which I will refer to here as a prefix, [...], then code#124, in
  164. this  special case, will be [...] plus  the first character of [...]. So
  165. just add the first character of [...] to the end of itself. Not too bad.
  166. As an example (and a very common one) of this special case, let's assume
  167. we  have  a raster image in which  the  first three pixels have the same
  168. color  value. That is, my charstream looks like: QQQ.... For the sake of
  169. argument,  let's  say  we  have 32 colors,  and  Q  is the color#12. The
  170. compressor will generate the code sequence 12,32,.... (if you don't know
  171. why,  take  a minute to understand it.)  Remember that #32 is not in the
  172. initial  table, which goes from #0 to #31. The decompressor will see #12
  173. and  translate it just fine as color Q. Then it will see #32 and not yet
  174. know  what  that  means. But if it  thinks  about it long enough, it can
  175. figure  out that QQ should be entry#32 in the table and QQ should be the
  176. next  string  output.  So the  decompression  pseudo-code goes something
  177. like:
  178.  
  179.       [1] Initialize string table;
  180.      [2] get first code: <code>;
  181.      [3] output the string for <code> to the charstream;
  182.      [4] <old> = <code>;
  183.      [5] <code> <- next code in codestream;
  184.      [6] does <code> exist in the string table?
  185.       (yes: output the string for <code> to the charstream;
  186.             [...] <- translation for <old>;
  187.             K <- first character of translation for <code>;
  188.             add [...]K to the string table;        <old> <- <code>;  )
  189.       (no: [...] <- translation for <old>;
  190.            K <- first character of [...];
  191.            output [...]K to charstream and add it to string table;
  192.            <old> <- <code>
  193.       )
  194.      [7] go to [5];
  195.  
  196.       Again,  when  you  get to step [5]  and  there  are no more codes,
  197. you're   finished.  Outputting  of  strings,   and  finding  of  initial
  198. characters in strings are efficiency problems all to themselves, but I'm
  199. not  going to suggest ways to do  them here. Half the fun of programming
  200. is  figuring  these  things out! --- Now  for  the GIF variations on the
  201. theme.  In  part of the header of a  GIF  file, there is a field, in the
  202. Raster  Data stream, called "code size".  This is a very misleading name
  203. for  the  field, but we have to live  with  it. What it is really is the
  204. "root size". The actual size, in bits, of the compression codes actually
  205. changes  during compression/decompression, and I will refer to that size
  206. here  as the "compression size". The initial table is just the codes for
  207. all  the  roots,  as usual, but two  special  codes  are added on top of
  208. those.  Suppose  you have a "code size",  which is usually the number of
  209. bits  per pixel in the image, of N.  If the number of bits/pixel is one,
  210. then  N  must  be 2: the roots take  up  slots  #0 and #1 in the initial
  211. table,  and  the two special codes will take  up slots #4 and #5. In any
  212. other  case,  N is the number of bits  per  pixel, and the roots take up
  213. slots #0 through #(2**N-1), and the special codes are (2**N) and (2**N +
  214. 1).  The  initial compression size will be  N+1 bits per code. If you're
  215. encoding,  you output the codes (N+1) bits  at a time to start with, and
  216. if  you're decoding, you grab (N+1) bits  from the codestream at a time.
  217. As  for the special codes: <CC> or the clear code, is (2**N), and <EOI>,
  218. or  end-of-information, is (2**N + 1).  <CC> tells the compressor to re-
  219. initialize the string table, and to reset the compression size to (N+1).
  220. <EOI>  means  there's no more in  the  codestream. If you're encoding or
  221. decoding,  you should start adding things to  the string table at <CC> +
  222. 2.  If  you're encoding, you should output  <CC> as the very first code,
  223. and then whenever after that you reach code #4095 (hex FFF), because GIF
  224. does  not allow compression sizes to be  greater than 12 bits. If you're
  225. decoding,  you  should reinitialize your  string  table when you observe
  226. <CC>.  The variable compression sizes are  really no big deal. If you're
  227. encoding, you start with a compression size of (N+1) bits, and, whenever
  228. you  output the code (2**(compression size)-1), you bump the compression
  229. size  up  one bit. So the next code  you  output will be one bit longer.
  230. Remember  that the largest compression size is 12 bits, corresponding to
  231. a  code  of 4095. If you get that  far, you must output <CC> as the next
  232. code,  and  start  over.  If you're  decoding,  you  must  increase your
  233. compression size AS SOON AS YOU write entry #(2**(compression size) - 1)
  234. to  the  string  table. The next code  you  READ will be one bit longer.
  235. Don't  make  the  mistake  of waiting until  you  need  to  add the code
  236. (2**compression  size)  to the table. You'll  have  already missed a bit
  237. from  the  last  code. The packaging of  codes  into  a bitsream for the
  238. raster  data is also a potential  stumbling block for the novice encoder
  239. or  decoder.  The lowest order bit in  the code should coincide with the
  240. lowest  available bit in the first available byte in the codestream. For
  241. example, if you're starting with 5-bit compression codes, and your first
  242. three  codes are, say, <abcde>, <fghij>, <klmno>,  where e, j, and o are
  243. bit#0, then your codestream will start off like:
  244.  
  245.        byte#0: hijabcde
  246.        byte#1: .klmnofg
  247.  
  248.       So  the  differences  between straight LZW  and  GIF  LZW are: two
  249. additional   special  codes  and  variable  compression  sizes.  If  you
  250. understand  LZW, and you understand  those variations, you understand it
  251. all!  Just as sort of a P.S., you may have noticed that a compressor has
  252. a  little bit of flexibility at compression time. I specified a "greedy"
  253. approach  to  the compression, grabbing  as  many characters as possible
  254. before outputting codes. This is, in fact, the standard LZW way of doing
  255. things,  and  it will yield the  best  compression ratio. But there's no
  256. rule  saying you can't stop anywhere along  the line and just output the
  257. code  for the current prefix, whether it's  already in the table or not,
  258. and  add that string plus the next  character to the string table. There
  259. are  various  reasons for wanting to  do this, especially if the strings
  260. get  extremely  long and make hashing difficult.  If you need to, do it.
  261. Hope this helps out.----steve blackstock
  262.  
  263. ---------------------------------------------------------------------------
  264. Article 5729 of comp.graphics:
  265. Path: polya!shelby!labrea!agate!ucbvax!tut.cis.ohio-state.edu!rutgers!cmcl2!phri!cooper!john
  266. >From: john@cooper.cooper.EDU (John Barkaus)
  267. Newsgroups: comp.graphics
  268. Subject: GIF file format responses 4/5
  269. Keywords: GIF LZW
  270. Message-ID: <1489@cooper.cooper.EDU>
  271. Date: 21 Apr 89 20:56:35 GMT
  272. Organization: The Cooper Union (NY, NY)
  273. Lines: 1050
  274.  
  275.  
  276. >From: cmcl2!neuron1.Jpl.Nasa.Gov!harry (Harry Langenbacher)
  277.  
  278.                                 G I F (tm)
  279.  
  280.                      Graphics Interchange Format (tm)
  281.  
  282.                       A standard defining a mechanism
  283.  
  284.                      for the storage and transmission
  285.  
  286.                    of raster-based graphics information
  287.  
  288.                                June 15, 1987
  289.  
  290.                      (c) CompuServe Incorporated, 1987
  291.  
  292.                             All rights reserved
  293.  
  294.             While this document is copyrighted, the information
  295.  
  296.           contained within is made available for use in computer
  297.  
  298.           software without royalties, or licensing restrictions.
  299.  
  300.           GIF and 'Graphics Interchange Format' are trademarks of
  301.  
  302.                          CompuServe, Incorporated.
  303.  
  304.                            an H&R Block Company
  305.  
  306.                         5000 Arlington Centre Blvd.
  307.  
  308.                            Columbus, Ohio 43220
  309.  
  310.                               (614) 457-8600
  311.  
  312.  
  313.  
  314.               Graphics Interchange Format (GIF) Specification
  315.  
  316.                              Table of Contents
  317.  
  318.         INTRODUCTION . . . . . . . . . . . . . . . . . page 3
  319.  
  320.         GENERAL FILE FORMAT  . . . . . . . . . . . . . page 3
  321.  
  322.         GIF SIGNATURE  . . . . . . . . . . . . . . . . page 4
  323.  
  324.         SCREEN DESCRIPTOR  . . . . . . . . . . . . . . page 4
  325.  
  326.         GLOBAL COLOR MAP . . . . . . . . . . . . . . . page 5
  327.  
  328.         IMAGE DESCRIPTOR . . . . . . . . . . . . . . . page 6
  329.  
  330.         LOCAL COLOR MAP  . . . . . . . . . . . . . . . page 7
  331.  
  332.         RASTER DATA  . . . . . . . . . . . . . . . . . page 7
  333.  
  334.         GIF TERMINATOR . . . . . . . . . . . . . . . . page 8
  335.  
  336.         GIF EXTENSION BLOCKS . . . . . . . . . . . . . page 8
  337.  
  338.         APPENDIX A - GLOSSARY  . . . . . . . . . . . . page 9
  339.  
  340.         APPENDIX B - INTERACTIVE SEQUENCES . . . . . . page 10
  341.  
  342.         APPENDIX C - IMAGE PACKAGING & COMPRESSION . . page 12
  343.  
  344.         APPENDIX D - MULTIPLE IMAGE PROCESSING . . . . page 15
  345.  
  346. Graphics Interchange Format (GIF)
  347.  
  348. Specification
  349.  
  350. INTRODUCTION
  351.  
  352.      'GIF'  (tm) is CompuServe's standard for defining generalized color
  353. raster   images.   This  'Graphics   Interchange   Format'  (tm)  allows
  354. high-quality,  high-resolution graphics to be  displayed on a variety of
  355. graphics  hardware and is intended as  an exchange and display mechanism
  356. for  graphics  images.  The image format  described  in this document is
  357. designed  to  support  current and future  image  technology and will in
  358. addition  serve as a basis for  future CompuServe graphics products. The
  359. main  focus  of  this document is  to  provide the technical information
  360. necessary  for  a programmer to implement  GIF encoders and decoders. As
  361. such,  some assumptions are made as  to terminology relavent to graphics
  362. and programming in general.
  363.  
  364.      The  first  section of this document  describes the GIF data format
  365. and its components and applies to all GIF decoders, either as standalone
  366. programs or as part of a communications package. Appendix B is a section
  367. relavent  to decoders that are part of a communications software package
  368. and  describes  the protocol requirements  for  entering and exiting GIF
  369. mode,  and  responding to host interrogations.  A glossary in Appendix A
  370. defines  some of the terminology used in this document. Appendix C gives
  371. a detailed explanation of how the graphics image itself is packaged as a
  372. series of data bytes.
  373.  
  374.                 Graphics Interchange Format Data Definition
  375.  
  376.  GENERAL FILE FORMAT
  377.  
  378.         +-----------------------+
  379.  
  380.         | +-------------------+ |
  381.  
  382.         | |   GIF Signature   | |
  383.  
  384.         | +-------------------+ |
  385.  
  386.         | +-------------------+ |
  387.  
  388.         | | Screen Descriptor | |
  389.  
  390.         | +-------------------+ |
  391.  
  392.         | +-------------------+ |
  393.  
  394.         | | Global Color Map  | |
  395.  
  396.         | +-------------------+ |
  397.  
  398.         . . .               . . .
  399.  
  400.         | +-------------------+ |    ---+
  401.  
  402.         | |  Image Descriptor | |       |
  403.  
  404.         | +-------------------+ |       |
  405.  
  406.         | +-------------------+ |       |
  407.  
  408.         | |  Local Color Map  | |       |-   Repeated 1 to n times
  409.  
  410.         | +-------------------+ |       |
  411.  
  412.         | +-------------------+ |       |
  413.  
  414.         | |    Raster Data    | |       |
  415.  
  416.         | +-------------------+ |    ---+
  417.  
  418.         . . .               . . .
  419.  
  420.         |-    GIF Terminator   -|
  421.  
  422.         +-----------------------+
  423.  
  424. Graphics Interchange Format (GIF)
  425.  
  426. Specification
  427.  
  428.  GIF SIGNATURE
  429.  
  430.      The  following  GIF  Signature identifies  the  data following as a
  431. valid GIF image stream. It consists of the following six characters:
  432.  
  433.              G I F 8 7 a
  434.  
  435.       The  last three characters '87a' may be viewed as a version number
  436. for  this  particular  GIF definition and will  be  used in general as a
  437. reference   in   documents  regarding  GIF   that  address  any  version
  438. dependencies.
  439.  
  440.  SCREEN DESCRIPTOR
  441.  
  442.      The  Screen Descriptor describes the overall parameters for all GIF
  443. images  following. It defines the overall  dimensions of the image space
  444. or  logical screen required, the existance of color mapping information,
  445. background  screen color, and color  depth information. This information
  446. is stored in a series of 8-bit bytes as described below.
  447.  
  448.               bits
  449.  
  450.          7 6 5 4 3 2 1 0  Byte #
  451.  
  452.         +---------------+
  453.  
  454.         |               |  1
  455.  
  456.         +-Screen Width -+      Raster width in pixels (LSB first)
  457.  
  458.         |               |  2
  459.  
  460.         +---------------+
  461.  
  462.         |               |  3
  463.  
  464.         +-Screen Height-+      Raster height in pixels (LSB first)
  465.  
  466.         |               |  4
  467.  
  468.         +-+-----+-+-----+      M = 1, Global color map follows Descriptor
  469.  
  470.         |M|  cr |0|pixel|  5   cr+1 = # bits of color resolution
  471.  
  472.         +-+-----+-+-----+      pixel+1 = # bits/pixel in image
  473.  
  474.         |   background  |  6   background=Color index of screen background
  475.  
  476.         +---------------+          (color is defined from the Global color
  477.  
  478.         |0 0 0 0 0 0 0 0|  7        map or default map if none specified)
  479.  
  480.         +---------------+
  481.  
  482.      The  logical  screen width and height  can  both be larger than the
  483. physical  display.  How  images  larger  than  the  physical display are
  484. handled  is implementation dependent and  can take advantage of hardware
  485. characteristics (e.g. Macintosh scrolling windows). Otherwise images can
  486. be  clipped  to  the  edges of the  display.  The  value of 'pixel' also
  487. defines  the  maximum  number of colors  within  an  image. The range of
  488. values  for  'pixel'  is  0  to 7  which  represents  1  to 8 bits. This
  489. translates  to  a range of 2 (B & W)  to  256 colors. Bit 3 of word 5 is
  490. reserved for future definition and must be zero.
  491.  
  492. Graphics Interchange Format (GIF)
  493.  
  494. Specification
  495.  
  496.  GLOBAL COLOR MAP
  497.  
  498.      The  Global Color Map is optional  but recommended for images where
  499. accurate  color rendition is desired. The existence of this color map is
  500. indicated  in the 'M' field of byte  5 of the Screen Descriptor. A color
  501. map  can  also be associated with each  image in a GIF file as described
  502. later. However this global map will normally be used because of hardware
  503. restrictions  in  equipment  available today.  In  the  individual Image
  504. Descriptors  the 'M' flag will normally be zero. If the Global Color Map
  505. is  present, it's definition immediately  follows the Screen Descriptor.
  506. The  number of color map entries  following a Screen Descriptor is equal
  507. to 2**(# bits per pixel), where each entry consists of three byte values
  508. representing   the   relative  intensities  of   red,   green  and  blue
  509. respectively. The structure of the Color Map block is:
  510.  
  511.               bits
  512.  
  513.          7 6 5 4 3 2 1 0  Byte #
  514.  
  515.         +---------------+
  516.  
  517.         | red intensity |  1    Red value for color index 0
  518.  
  519.         +---------------+
  520.  
  521.         |green intensity|  2    Green value for color index 0
  522.  
  523.         +---------------+
  524.  
  525.         | blue intensity|  3    Blue value for color index 0
  526.  
  527.         +---------------+
  528.  
  529.         | red intensity |  4    Red value for color index 1
  530.  
  531.         +---------------+
  532.  
  533.         |green intensity|  5    Green value for color index 1
  534.  
  535.         +---------------+
  536.  
  537.         | blue intensity|  6    Blue value for color index 1
  538.  
  539.         +---------------+
  540.  
  541.         :               :       (Continues for remaining colors)
  542.  
  543.      Each  image pixel value received will be displayed according to its
  544. closest match with an available color of the display based on this color
  545. map.  The  color components represent  a fractional intensity value from
  546. none  (0)  to full (255). White  would  be represented as (255,255,255),
  547. black  as (0,0,0) and medium yellow  as (180,180,0). For display, if the
  548. device  supports fewer than 8 bits per color component, the higher order
  549. bits  of  each  component are used. In  the  creation of a GIF color map
  550. entry  with  hardware  supporting fewer than  8  bits per component, the
  551. component  values  for  the hardware should  be  converted  to the 8-bit
  552. format with the following calculation:
  553.  
  554.         <map_value> = <component_value>*255/(2**<nbits> -1)
  555.  
  556.       This  assures accurate translation of  colors for all displays. In
  557. the  cases  of creating GIF images  from  hardware without color palette
  558. capability,  a  fixed palette should be  created  based on the available
  559. display colors for that hardware. If no Global Color Map is indicated, a
  560. default  color  map  is generated  internally  which  maps each possible
  561. incoming color index to the same hardware color index modulo <n> where
  562.  
  563.    <n> is the number of available hardware colors.
  564.  
  565. Graphics Interchange Format (GIF)
  566.  
  567. Specification
  568.  
  569.  IMAGE DESCRIPTOR
  570.  
  571.      The  Image  Descriptor defines the  actual placement and extents of
  572. the  following image within the space  defined in the Screen Descriptor.
  573. Also  defined are flags to indicate the presence of a local color lookup
  574. map,  and to define the pixel display sequence. Each Image Descriptor is
  575. introduced  by  an  image  separator character.  The  role  of the Image
  576. Separator  is simply to provide a synchronization character to introduce
  577. an  Image Descriptor. This is desirable if a GIF file happens to contain
  578. more  than  one  image.  This character is  defined  as  0x2C hex or ','
  579. (comma).  When  this character is  encountered between images, the Image
  580. Descriptor  will follow immediately.  Any characters encountered between
  581. the  end of a previous image and the image separator character are to be
  582. ignored.  This  allows  future GIF enhancements  to  be present in newer
  583. image formats and yet ignored safely by older software decoders.
  584.  
  585.               bits
  586.  
  587.          7 6 5 4 3 2 1 0  Byte #
  588.  
  589.         +---------------+
  590.  
  591.         |0 0 1 0 1 1 0 0|  1    ',' - Image separator character
  592.  
  593.         +---------------+
  594.  
  595.         |               |  2    Start of image in pixels from the
  596.  
  597.         +-  Image Left -+       left side of the screen (LSB first)
  598.  
  599.         |               |  3
  600.  
  601.         +---------------+
  602.  
  603.         |               |  4
  604.  
  605.         +-  Image Top  -+       Start of image in pixels from the
  606.  
  607.         |               |  5    top of the screen (LSB first)
  608.  
  609.         +---------------+
  610.  
  611.         |               |  6
  612.  
  613.         +- Image Width -+       Width of the image in pixels (LSB first)
  614.  
  615.         |               |  7
  616.  
  617.         +---------------+
  618.  
  619.         |               |  8
  620.  
  621.         +- Image Height-+       Height of the image in pixels (LSB first)
  622.  
  623.         |               |  9
  624.  
  625.         +-+-+-+-+-+-----+       M=0 - Use global color map, ignore 'pixel'
  626.  
  627.         |M|I|0|0|0|pixel| 10    M=1 - Local color map follows, use 'pixel'
  628.  
  629.         +-+-+-+-+-+-----+       I=0 - Image formatted in Sequential order
  630.  
  631.                                 I=1 - Image formatted in Interlaced order
  632.  
  633.                                 pixel+1 - # bits per pixel for this image
  634.  
  635.      The specifications for the image position and size must be confined
  636. to the dimensions defined by the Screen Descriptor. On the other hand it
  637. is not necessary that the image fill the entire screen defined.
  638.  
  639.  LOCAL COLOR MAP
  640.  
  641. Graphics Interchange Format (GIF)
  642.  
  643. Specification
  644.  
  645.      A  Local Color Map is optional and  defined here for future use. If
  646. the  'M' bit of byte 10 of the Image Descriptor is set, then a color map
  647. follows  the Image Descriptor that applies  only to the following image.
  648. At the end of the image, the color map will revert to that defined after
  649. the Screen Descriptor. Note that the 'pixel' field of byte 10 of the
  650.  
  651. Image  Descriptor  is used only if a  Local Color Map is indicated. This
  652. defines the parameters not only for the image pixel size, but determines
  653. the  number  of color map entries that  follow. The bits per pixel value
  654. will  also  revert to the value  specified in the Screen Descriptor when
  655. processing of the image is complete.
  656.  
  657.  RASTER DATA
  658.  
  659.      The  format  of the actual image is  defined as the series of pixel
  660. color index values that make up the image. The pixels are stored left to
  661. right  sequentially  for  an  image row.  By  default  each image row is
  662. written  sequentially, top to bottom. In  the case that the Interlace or
  663. 'I' bit is set in byte 10 of the Image Descriptor then the row order of
  664. the  image  display  follows a four-pass  process  in which the image is
  665. filled  in  by widely spaced rows. The  first pass writes every 8th row,
  666. starting  with  the top row of the  image window. The second pass writes
  667. every  8th  row starting at the fifth  row  from the top. The third pass
  668. writes  every 4th row starting at the third row from the top. The fourth
  669. pass  completes  the  image, writing every  other  row,  starting at the
  670. second row from the top. A graphic description of this process follows:
  671.  
  672.    Image
  673.  
  674.    Row  Pass 1  Pass 2  Pass 3  Pass 4          Result
  675.  
  676.    ---------------------------------------------------
  677.  
  678.      0  **1a**                                  **1a**
  679.  
  680.      1                          **4a**          **4a**
  681.  
  682.      2                  **3a**                  **3a**
  683.  
  684.      3                          **4b**          **4b**
  685.  
  686.      4          **2a**                          **2a**
  687.  
  688.      5                          **4c**          **4c**
  689.  
  690.      6                  **3b**                  **3b**
  691.  
  692.      7                          **4d**          **4d**
  693.  
  694.      8  **1b**                                  **1b**
  695.  
  696.      9                          **4e**          **4e**
  697.  
  698.     10                  **3c**                  **3c**
  699.  
  700.     11                          **4f**          **4f**
  701.  
  702.     12          **2b**                          **2b**
  703.  
  704.    . . .
  705.  
  706.      The  image pixel values are processed  as a series of color indices
  707. which  map  into the existing color  map. The resulting color value from
  708. the map is what is actually displayed. This series of pixel indices, the
  709. number  of which is equal to image-width*image-height pixels, are passed
  710. to  the  GIF  image  data stream  one  value  per  pixel, compressed and
  711. packaged  according  to  a version of  the  LZW compression algorithm as
  712. defined in Appendix C.
  713.  
  714. Graphics Interchange Format (GIF)
  715.  
  716. Specification
  717.  
  718.  GIF TERMINATOR
  719.  
  720.      In  order to provide a synchronization for the termination of a GIF
  721. image  file,  a  GIF decoder will process  the  end of GIF mode when the
  722. character 0x3B hex or ';' is found after an image has been processed. By
  723. convention  the  decoding  software will pause  and  wait  for an action
  724. indicating  that  the user is ready to  continue. This may be a carriage
  725. return  entered  at  the  keyboard or  a  mouse  click.  For interactive
  726. applications  this  user  action  must be passed  on  to  the  host as a
  727. carriage return character so that the host application can continue. The
  728. decoding software will then typically leave graphics mode and resume any
  729. previous process.
  730.  
  731.  GIF EXTENSION BLOCKS
  732.  
  733.      To provide for orderly extension of the GIF definition, a mechanism
  734. for  defining  the packaging of extensions  within  a GIF data stream is
  735. necessary.  Specific GIF extensions are to  be defined and documented by
  736. CompuServe  in  order  to  provide  a  controlled  enhancement path. GIF
  737. Extension  Blocks  are packaged in a manner  similar to that used by the
  738. raster data though not compressed. The basic structure is:
  739.  
  740.          7 6 5 4 3 2 1 0  Byte #
  741.  
  742.         +---------------+
  743.  
  744.         |0 0 1 0 0 0 0 1|  1       '!' - GIF Extension Block Introducer
  745.  
  746.         +---------------+
  747.  
  748.         | function code |  2       Extension function code (0 to 255)
  749.  
  750.         +---------------+    ---+
  751.  
  752.         |  byte count   |       |
  753.  
  754.         +---------------+       |
  755.  
  756.         :               :       +-- Repeated as many times as necessary
  757.  
  758.         |func data bytes|       |
  759.  
  760.         :               :       |
  761.  
  762.         +---------------+    ---+
  763.  
  764.         . . .       . . .
  765.  
  766.         +---------------+
  767.  
  768.         |0 0 0 0 0 0 0 0|       zero byte count (terminates block)
  769.  
  770.         +---------------+
  771.  
  772.      A  GIF Extension Block may immediately preceed any Image Descriptor
  773. or  occur  before the GIF Terminator. All  GIF  decoders must be able to
  774. recognize  the  existence of GIF Extension  Blocks and read past them if
  775. unable  to  process the function code.  This ensures that older decoders
  776. will  be able to process extended GIF  image files in the future, though
  777. without the additional functionality.
  778.  
  779. Graphics Interchange Format (GIF)                                    Page 9
  780.  
  781. Appendix A - Glossary
  782.  
  783.                                  GLOSSARY
  784.  
  785. Pixel  - The smallest picture element  of a graphics image. This usually
  786.    corresponds to a single dot on a graphics screen. Image resolution is
  787.    typically  given  in units of pixels.  For  example a fairly standard
  788.    graphics  screen format is one 320 pixels across and 200 pixels high.
  789.    Each  pixel  can  appear as one  of  several  colors depending on the
  790.    capabilities of the graphics hardware.
  791.  
  792. Raster - A horizontal row of pixels representing one line of an image. A
  793.    typical method of working with images since most hardware is oriented
  794.    to work most efficiently in this manner.
  795.  
  796. LSB  -  Least  Significant  Byte. Refers  to  a  convention for two byte
  797.    numeric  values  in  which  the less  significant  byte  of the value
  798.    preceeds  the  more significant byte.  This  convention is typical on
  799.    many microcomputers.
  800.  
  801. Color  Map - The list of definitions of  each color used in a GIF image.
  802.    These  desired  colors  are converted  to  available colors through a
  803.    table which is derived by assigning an incoming color index (from the
  804.    image)  to  an output color index  (of the hardware). While the color
  805.    map  definitons are specified in a GIF image, the output pixel colors
  806.    will  vary  based on the hardware used  and  its ability to match the
  807.    defined color.
  808.  
  809. Interlace  -  The  method of displaying  a  GIF  image in which multiple
  810.    passes  are  made, outputting raster lines  spaced apart to provide a
  811.    way  of visualizing the general content of an entire image before all
  812.    of the data has been processed.
  813.  
  814. B  Protocol  -  A  CompuServe-developed  error-correcting  file transfer
  815.    protocol available in the public domain and implemented in CompuServe
  816.    VIDTEX  products.  This  error  checking  mechanism  will  be used in
  817.    transfers of GIF images for interactive applications.
  818.  
  819. LZW  - A sophisticated data compression  algorithm based on work done by
  820.    Lempel-Ziv  & Welch which has the  feature of very efficient one-pass
  821.    encoding  and decoding. This allows the  image to be decompressed and
  822.    displayed  at  the  same time. The  original  article from which this
  823.    technique was adapted is:
  824.  
  825.           Terry  A.   Welch,  "A  Technique  for  High   Performance   Data
  826.  
  827.           Compression", IEEE Computer, vol 17 no 6 (June 1984)
  828.  
  829.      This  basic  algorithm is also used  in  the public domain ARC file
  830. compression  utilities.  The  CompuServe adaptation  of  LZW  for GIF is
  831. described in Appendix C.
  832.  
  833. Graphics Interchange Format (GIF)
  834.  
  835. Appendix B - Interactive Sequences
  836.  
  837.    GIF  Sequence Exchanges for an  Interactive Environment The following
  838. sequences  are defined for use in mediating control between a GIF sender
  839. and   GIF  receiver  over  an  interactive  communications  line.  These
  840. sequences  do  not  apply to  applications  that  involve downloading of
  841. static GIF files and are not considered part of a GIF file.
  842.  
  843.  GIF CAPABILITIES ENQUIRY
  844.  
  845.      The  GCE sequence is issued from a host and requests an interactive
  846. GIF  decoder  to  return a response  message  that  defines the graphics
  847. parameters  for  the decoder. This  involves returning information about
  848. available screen sizes, number of bits/color supported and the amount of
  849. color detail supported. The escape sequence for the GCE is defined as:
  850.  
  851.         ESC [ > 0 g     (g is lower case, spaces inserted for clarity)
  852.  
  853.                          (0x1B 0x5B 0x3E 0x30 0x67)
  854.  
  855.  GIF CAPABILITIES RESPONSE
  856.  
  857.      The GIF Capabilities Response message is returned by an interactive
  858. GIF  decoder  and  defines the  decoder's  display  capabilities for all
  859. graphics  modes  that are supported by  the software. Note that this can
  860. also include graphics printers as well as a monitor screen. The general
  861.  
  862.    format of this message is:
  863.  
  864.      #version;protocol{;dev, width, height, color-bits, color-res}... <CR>
  865.  
  866.    '#'          - GCR identifier character (Number Sign)
  867.  
  868.    version      - GIF format version number;  initially '87a'
  869.  
  870.    protocol='0' - No end-to-end protocol supported by decoder
  871.  
  872.                   Transfer as direct 8-bit data stream.
  873.  
  874.    protocol='1' - Can use an error correction protocol to transfer GIF data
  875.  
  876.                interactively from the host directly to the display.
  877.  
  878.    dev = '0'    - Screen parameter set follows
  879.  
  880.    dev = '1'    - Printer parameter set follows
  881.  
  882.    width- Maximum supported display width in pixels
  883.  
  884.    height       - Maximum supported display height in pixels
  885.  
  886.    color-bits   - Number of  bits  per  pixel  supported.   The  number  of
  887.  
  888.                supported colors is therefore 2**color-bits.
  889.  
  890.    color-res    - Number of bits  per  color  component  supported  in  the
  891.  
  892.                hardware  color  palette.   If  color-res  is  '0'  then  no
  893.  
  894.                hardware palette table is available.
  895.  
  896.      Note  that  all  values in the  GCR  are  returned as ASCII decimal
  897. numbers and the message is terminated by a Carriage Return character.
  898.  
  899. Graphics Interchange Format (GIF)
  900.  
  901. Appendix B - Interactive Sequences
  902.  
  903.      The   following   GCR   message   describes   three   standard  EGA
  904. configurations  with  no printer; the GIF  data  stream can be processed
  905. within an error correcting protocol:
  906.  
  907.         #87a;1 ;0,320,200,4,0 ;0,640,200,2,2 ;0,640,350,4,2<CR>
  908.  
  909.  ENTER GIF GRAPHICS MODE
  910.  
  911.        Two  sequences are currently defined to invoke an interactive GIF
  912. decoder  into action. The only difference between them is that different
  913. output media are selected. These sequences are:
  914.  
  915.      ESC [ > 1 g   Display GIF image on screen
  916.  
  917.                    (0x1B 0x5B 0x3E 0x31 0x67)
  918.  
  919.      ESC [ > 2 g   Display image directly to an attached graphics  printer.
  920.  
  921.                    The  image  may optionally be displayed on the screen as
  922.  
  923.                    well.
  924.  
  925.                    (0x1B 0x5B 0x3E 0x32 0x67)
  926.  
  927.      Note  that the 'g' character terminating  each sequence is in lower
  928. case.
  929.  
  930.  INTERACTIVE ENVIRONMENT
  931.  
  932.      The assumed environment for the transmission of GIF image data from
  933. an  interactive  application  is a full  8-bit  data stream from host to
  934. micro.  All 256 character codes  must be transferrable. The establishing
  935. of  an 8-bit data path for communications will normally be taken care of
  936. by  the  host  application programs. It  is  however up to the receiving
  937. communications programs supporting GIF to be able to receive and pass on
  938. all 256 8-bit codes to the GIF decoder software.
  939.  
  940. Graphics Interchange Format (GIF)
  941.  
  942. Appendix C - Image Packaging & Compression
  943.  
  944.         The  Raster Data stream that  represents the actual output image
  945. can be represented as:
  946.  
  947.          7 6 5 4 3 2 1 0
  948.  
  949.         +---------------+
  950.  
  951.         |   code size   |
  952.  
  953.         +---------------+     ---+
  954.  
  955.         |blok byte count|        |
  956.  
  957.         +---------------+        |
  958.  
  959.         :               :        +-- Repeated as many times as necessary
  960.  
  961.         |  data bytes   |        |
  962.  
  963.         :               :        |
  964.  
  965.         +---------------+     ---+
  966.  
  967.         . . .       . . .
  968.  
  969.         +---------------+
  970.  
  971.         |0 0 0 0 0 0 0 0|       zero byte count (terminates data stream)
  972.  
  973.         +---------------+
  974.  
  975.         The  conversion of the image from a  series of pixel values to a
  976. transmitted  or stored character stream involves several steps. In brief
  977. these steps are:
  978.  
  979. 1.  Establish  the  Code  Size - Define  the  number  of  bits needed to
  980.     represent the actual data.
  981.  
  982. 2.  Compress the Data - Compress the  series of image pixels to a series
  983.     of compression codes.
  984.  
  985. 3.  Build  a  Series of Bytes -  Take  the  set of compression codes and
  986.     convert to a string of 8-bit bytes.
  987.  
  988. 4.  Package  the Bytes - Package sets  of bytes into blocks preceeded by
  989.     character counts and output.
  990.  
  991. ESTABLISH CODE SIZE
  992.  
  993.      The  first byte of the GIF Raster Data stream is a value indicating
  994. the minimum number of bits required to represent the set of actual pixel
  995. values.  Normally  this  will be the same  as  the number of color bits.
  996. Because  of  some algorithmic constraints  however, black & white images
  997. which  have one color bit must be indicated  as having a code size of 2.
  998. This  code size value also implies that the compression codes must start
  999. out one bit longer.
  1000.  
  1001. COMPRESSION
  1002.  
  1003.      The LZW algorithm converts a series of data values into a series of
  1004. codes  which may be raw values or a code designating a series of values.
  1005. Using  text  characters  as an analogy,  the  output  code consists of a
  1006. character or a code representing a string of characters.
  1007.  
  1008. Graphics Interchange Format (GIF)
  1009.  
  1010. Appendix C - Image Packaging & Compression
  1011.  
  1012.      The  LZW  algorithm  used in  GIF  matches algorithmically with the
  1013. standard LZW algorithm with the following differences:
  1014.  
  1015. 1.    A    special   Clear   code    is   defined   which   resets   all
  1016.     compression/decompression parameters and tables to a start-up state.
  1017.     The  value  of this code is 2**<code  size>. For example if the code
  1018.     size  indicated was 4 (image was  4 bits/pixel) the Clear code value
  1019.     would  be 16 (10000 binary). The Clear  code can appear at any point
  1020.     in the image data stream and therefore requires the LZW algorithm to
  1021.     process  succeeding  codes  as if a  new  data  stream was starting.
  1022.     Encoders  should output a Clear code as the first code of each image
  1023.     data stream.
  1024.  
  1025. 2.  An End of Information code  is defined that explicitly indicates the
  1026.     end  of  the image data stream.  LZW processing terminates when this
  1027.     code  is encountered. It must be the last code output by the encoder
  1028.     for an image. The value of this code is <Clear code>+1.
  1029.  
  1030. 3. The first available compression code value is <Clear code>+2.
  1031.  
  1032. 4.  The  output codes are of  variable length, starting at <code size>+1
  1033.  bits  per  code,  up to 12 bits  per  code. This defines a maximum code
  1034.  value  of 4095 (hex FFF). Whenever the  LZW code value would exceed the
  1035.  current  code  length,  the  code  length  is  increased  by  one.  The
  1036.  packing/unpacking  of  these codes must then  be altered to reflect the
  1037.  new code length.
  1038.  
  1039. BUILD 8-BIT BYTES
  1040.  
  1041.      Because  the  LZW  compression  used for  GIF  creates  a series of
  1042. variable  length codes, of between 3 and  12 bits each, these codes must
  1043. be  reformed  into a series of 8-bit  bytes  that will be the characters
  1044. actually  stored or transmitted. This provides additional compression of
  1045. the  image.  The codes are formed into a  stream of bits as if they were
  1046. packed right to left and then picked off 8 bits at a time to be output.
  1047.  
  1048. Assuming a character array of 8 bits per character and using 5 bit codes
  1049. to be packed, an example layout would be similar to:
  1050.  
  1051.          byte n       byte 5   byte 4   byte 3   byte 2   byte 1
  1052.  
  1053.         +-.....-----+--------+--------+--------+--------+--------+
  1054.  
  1055.         | and so on |hhhhhggg|ggfffffe|eeeedddd|dcccccbb|bbbaaaaa|
  1056.  
  1057.         +-.....-----+--------+--------+--------+--------+--------+
  1058.  
  1059.         Note that the physical  packing  arrangement  will  change  as  the
  1060.    number  of  bits per compression code change but the concept remains the
  1061.    same.
  1062.  
  1063. PACKAGE THE BYTES
  1064.  
  1065.      Once  the bytes have been created, they are grouped into blocks for
  1066. output by preceeding each block of 0 to 255 bytes with a character count
  1067. byte.  A block with a zero byte  count terminates the Raster Data stream
  1068. for a given image. These blocks are what are actually output for the
  1069.  
  1070. Graphics Interchange Format (GIF)
  1071. Appendix C - Image Packaging & Compression
  1072.  
  1073. GIF  image. This block format has the side effect of allowing a decoding
  1074. program  the ability to read past the  actual image data if necessary by
  1075. reading block counts and then skipping over the data.
  1076.  
  1077. Graphics Interchange Format (GIF)
  1078.  
  1079. Appendix D - Multiple Image Processing
  1080.  
  1081.      Since  a  GIF  data  stream  can  contain  multiple  images,  it is
  1082. necessary to describe processing and display of such a file. Because the
  1083. image  descriptor  allows for placement of  the image within the logical
  1084. screen, it is possible to define a sequence of images that may each be a
  1085. partial  screen, but in total fill the entire screen. The guidelines for
  1086. handling the multiple image situation are:
  1087.  
  1088. 1.  There  is no pause between  images. Each is processed immediately as
  1089.     seen by the decoder.
  1090.  
  1091. 2.  Each  image  explicitly overwrites any  image  already on the screen
  1092.     inside  of  its window. The only  screen clears are at the beginning
  1093.     and  end  of  the  GIF  image  process.  See  discussion  on the GIF
  1094.     terminator.
  1095.  
  1096.  
  1097.